package smartcrud.spring.models.rbac;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import smartcrud.common.orm.Page;
import smartcrud.common.orm.PropertyFilter;

@Service
public class UserServiceJdbcImpl implements UserService {
	@Autowired
	private UserDao userDao;

	@Override
	public User createUser(User o) {
		User user = userDao.createUser(o);
		userDao.assignUserWithRoles(user);
		return user;
	}

	@Override
	public void deleteUser(Long id) {
		userDao.deleteUser(id);
	}

	@Override
	public void updateUser(User o) {
		userDao.updateUser(o);
		userDao.assignUserWithRoles(o);
	}

	@Override
	public User findUserById(Long id) {
		return userDao.findUserById(id);
	}

	@Override
	public List<User> findAllUsers() {
		return userDao.findAllUsers();
	}

	@Override
	public Page<User> findByPage(Page<User> page, final List<PropertyFilter> filters) {
		return userDao.findByPage(page,filters);
	}
	
	@Override
	public User connect(String email, String password) {
//		String encrypted = MD5.encrypt(password);
		return userDao.connect(email, password);
	}

	@Override
	public List<Menu> getUserMenus(Long userId) {
		return userDao.getUserMenus(userId);
	}
	
	public String getMenuAsString(HttpServletRequest req, Long userId) {
		List<Menu> menus = getUserMenus(userId);
		StringBuffer sb = new StringBuffer();
		for (Menu menu : menus) {
			if (menu.getLevel() == 1) {
				sb.append("<li class='nav-header'>" + menu.getName() + "</li>");
			} else {
				sb.append("<li><a href='"+req.getContextPath() + menu.getUrl() + "'>" + menu.getName()+ "</a></li>");
			}
		}
		return sb.toString();
	}
}
